package cn.simple.manager.web;

import cn.simple.manager.configuration.DynamicDataSourceHolder;
import cn.simple.manager.todo.ResponseEntity;
import cn.simple.manager.todo.TodoCrudService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController()
@CrossOrigin
public class CurdController {

    @Autowired
    TodoCrudService service;

    @PostMapping("/{type}/select")
    public List<Map<String, Object>>  select(@PathVariable(required = false) String type,@RequestBody String sql){
        DynamicDataSourceHolder.setHolder(type);
        try{
            return service.select(sql);
        }catch (Exception e){
            throw e;
        }finally {
            DynamicDataSourceHolder.clear();
        }
    }

    @PostMapping("/{type}/update")
    public ResponseEntity update(@PathVariable(required = false) String type,@RequestBody String sql){
        DynamicDataSourceHolder.setHolder(type);
        try{
            return ResponseEntity.ok(service.update(sql));
        }catch (Exception e){
            throw e;
        }finally {
            DynamicDataSourceHolder.clear();
        }
    }


    @PostMapping("/{type}/insert")
    public ResponseEntity insert(@PathVariable(required = false) String type ,@RequestBody String sql){
        DynamicDataSourceHolder.setHolder(type);
        try{
            service.insert(sql);
            return ResponseEntity.ok(null);
        }catch (Exception e){
            throw e;
        }finally {
            DynamicDataSourceHolder.clear();
        }
    }

    @PostMapping("/{type}/delete")
    public ResponseEntity delete(@PathVariable(required = false) String type ,@RequestBody String sql){
        DynamicDataSourceHolder.setHolder(type);
        try{
            return ResponseEntity.ok(service.delete(sql));
        }catch (Exception e){
            throw e;
        }finally {
            DynamicDataSourceHolder.clear();
        }
    }

}
